package cake.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import cake.dao.CakeDao;
import cake.dao.CategoryDao;
import cake.dao.CommentDao;
import cake.dao.impl.CakeDaoImpl;
import cake.dao.impl.CategoryDaoImpl;
import cake.dao.impl.CommentDaoImpl;
import cake.entity.Cake;
import cake.entity.Category;
import cake.entity.Comment;


@WebServlet("/admin/comm.html")
public class AdminComm extends HttpServlet{

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		CommentDao commentDao = new CommentDaoImpl();
		
		String did = req.getParameter("did");
		if(did!=null && did!="") {
			int id = Integer.parseInt(did);
			commentDao.deleteComment(id);
		}
		
		CategoryDao categoryDao = new CategoryDaoImpl();
		List<Category> categories = categoryDao.getAllCategory();
		req.setAttribute("categories", categories);
		
		CakeDao cakeDao =  new CakeDaoImpl();
		Category category = null;
		List<Cake> cakes = null;
		int categoryid = 0;
		if(req.getParameter("categoryid")!=null && req.getParameter("categoryid")!="") {
			categoryid  = Integer.parseInt(req.getParameter("categoryid"));
		    category = categoryDao.getCategoryById(categoryid);
		    cakes = cakeDao.getCakeByCategoryId(categoryid);
		}
		req.setAttribute("category", category);
		req.setAttribute("cakes", cakes);
		req.setAttribute("categoryid", categoryid);
		
		final int pageSize = 10;
		int cid = 0;
		if(req.getParameter("cid")!=null && req.getParameter("cid")!=""){
    		cid = Integer.parseInt(req.getParameter("cid"));
    	}
    	req.setAttribute("cid", cid);
		String title = "";
    	if(req.getParameter("title")!=null && req.getParameter("title")!=""){
    		title = req.getParameter("title");
    	}
    	req.setAttribute("title", title);
    	int rows = commentDao.fetchCommentRowsUC(cid,title);
    	int totalPages = rows%pageSize==0?(rows/pageSize):(rows/pageSize+1);
    	req.setAttribute("totalPages", totalPages);
    	
    	int pageNum = 1;
		if(req.getParameter("page")!=null) {
			pageNum = Integer.parseInt(req.getParameter("page"));
		}
		req.setAttribute("pageNum", pageNum);
		List<Comment> comments = commentDao.getUserAndCake(cid,title,pageSize,pageNum);
		req.setAttribute("comments", comments);
		 
		req.getRequestDispatcher("Comm.jsp").forward(req, resp);
	}

}
